package com.heima.behavior.interceptor;

import com.heima.common.exception.CustomException;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.ApUserThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class AppTokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头中FeignAuthorization:feignpass ,如果是feign之间的 相互调用,直接放行
        String feignAuthorization = request.getHeader("FeignAuthorization");
        if (com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotBlank(feignAuthorization) && feignAuthorization.equals("feignpass")) {
            //放行
            return true;
        }

        //获取请求头中的userId
        String userId = request.getHeader("userId");
        if (StringUtils.isEmpty(userId)) {
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }
      //  log.info("userId:{}", userId);
        //存入到当前线程中
        ApUser apUser = new ApUser();
        apUser.setId(Integer.valueOf(userId));
        ApUserThreadLocalUtil.setUser(apUser);
        return true;

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清理ThreadLocal
        ApUserThreadLocalUtil.clear();
    }
}
